/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "ListBox.h"
#include "view/ListBox.h"

namespace liba
{
namespace lib2d
{
namespace gui
{

namespace listbox
{
Item::Item( ListBox * parent )
:	Button/*Object*/( parent->get_container(), Rect( 0, 0, 100, 12 ) ),
	list_box( parent )
{
	list_box->insert( this );
}
Item::~Item()
{
	list_box->erase( this );
}
}

ListBox::ListBox( Object * parent )
:	Object( parent, Rect( 150, 50, 120, 100 ) ),
	length( 0 )
{
	container = new SimpleContainer( this );
	scroll_bar = new ScrollBar( this );

	view = new view::ListBox( this );
}

ListBox::~ListBox()
{}

void ListBox::adjust_scroll_bar()
{
	if( length > get_client_rect().height )
	{
		scroll_bar->set_range( 0, length - get_client_rect().height );
		scroll_bar->set_page_size( get_client_rect().height/length );
	}
	else
	{
		scroll_bar->set_range( 0, 0 );
		scroll_bar->set_page_size( 1 );
	}

	scroll_bar->set_position( 0 );
}

void ListBox::insert( listbox::Item * item )
{
	//TODO insert

	item->adjust_position( length );
	length += item->get_height();
	adjust_scroll_bar();
}

void ListBox::erase( listbox::Item * item )
{
	//TODO remove
	length -= item->get_height();
	adjust_scroll_bar();
}

void ListBox::on_button_down( const Vector2 & point, const Atom & button_name )
{
	Vector2 new_point = point + Vector2( 0, scroll_bar->get_position() );
	container->on_button_down( new_point, button_name );
	Object::on_button_down( point, button_name );
}

void ListBox::on_button_up( const Vector2 & point, const Atom & button_name )
{
	Vector2 new_point = point + Vector2( 0, scroll_bar->get_position() );
	container->on_button_up( new_point, button_name );
	Object::on_button_up( point, button_name );
}

void ListBox::on_mouse_move( const Vector2 & point )
{
	Vector2 new_point = point + Vector2( 0, scroll_bar->get_position() );
	container->on_mouse_move( new_point );
	Object::on_mouse_move( point );
}

void ListBox::on_mouse_out()
{
	container->on_mouse_out();
	Object::on_mouse_out();
}

} //namespace gui
} //namespace lib2d
} //namespace liba

